package com.yunti.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.yunti.business.domain.*;
import com.yunti.business.mapper.*;
import com.yunti.business.service.IOchestrateService;
import com.yunti.business.utils.LotteryUtil;
import com.yunti.business.vo.req.OrchestrateReq;
import com.yunti.business.vo.res.OrchestrateRes;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTRPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

@Service
public class OrchestrateServiceImpl extends ServiceImpl<OchestrateMapper, Ochestrate> implements IOchestrateService {

    @Autowired
    private BaseRaceMapper baseRaceMapper;

    @Resource
    private BaseSubjectMapper baseSubjectMapper;

    @Resource
    private BaseStudentMapper baseStudentMapper;

    @Resource
    private BaseSchoolMapper baseSchoolMapper;

    @Resource
    private OchestrateMapper ochestrateMapper;


    @Override
    public TableDataInfo list(OrchestrateReq baseSubjectReq, Integer pageNum, Integer pageSize) {
        List<OrchestrateRes> orchestrateList = new ArrayList<>();
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long raecId = loginUser.getSelectRaceId();
        Long schoolId = baseSubjectReq.getSchoolId();


        Long total = 0L;

        if (baseSubjectReq.getSubId() == null) {

        }
        BaseSubject baseSubject = baseSubjectMapper.selectById(baseSubjectReq.getSubId());

        //个人项目
        if (Integer.valueOf(1).equals(baseSubject.getType())) {
            List<BaseStudent> baseStudentList = new ArrayList<>();
            BaseSubject parentBaseSubject = null;
            if (baseSubject.getParentId() != null) {
                parentBaseSubject = baseSubjectMapper.selectById(baseSubject.getParentId());
            }

            //如果是抽签的项目
            if (parentBaseSubject != null && parentBaseSubject.getLottery() == 1) {
                LambdaQueryWrapper<BaseStudent> baseStudentLambdaQueryWrapper = new LambdaQueryWrapper<>();
                baseStudentLambdaQueryWrapper.eq(BaseStudent::getTwoConfirm, 1);
                baseStudentLambdaQueryWrapper.eq(BaseStudent::getRaceId, raecId);
                if (baseSubjectReq.getSchoolId() != null) {
                    baseStudentLambdaQueryWrapper.eq(BaseStudent::getSchoolId, baseSubjectReq.getSchoolId());
                }
                List<BaseStudent> totalBaseStudent = baseStudentMapper.selectList(baseStudentLambdaQueryWrapper);
                List<Ochestrate> ochestrateList = new ArrayList<>();
                if (totalBaseStudent.size() > 0) {
                    LambdaQueryWrapper<Ochestrate> ochestrateLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    ochestrateLambdaQueryWrapper.eq(Ochestrate::getSubId, parentBaseSubject.getId());
                    ochestrateLambdaQueryWrapper.eq(Ochestrate::getElectiveSubId, baseSubject.getId());
                    ochestrateLambdaQueryWrapper.eq(Ochestrate::getObjectType, 1);
                    ochestrateLambdaQueryWrapper.in(Ochestrate::getObjectId, totalBaseStudent.stream().map(BaseStudent::getId).collect(Collectors.toList()));
                    ochestrateList = baseMapper.selectList(ochestrateLambdaQueryWrapper);
                }
                if (ochestrateList.size() > 0) {
//                    LambdaQueryWrapper<BaseStudent> baseStudentLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
//                    baseStudentLambdaQueryWrapper2.in(BaseStudent::getId, ochestrateList.stream().map(Ochestrate::getObjectId).collect(Collectors.toList()));
//                    baseStudentList = baseStudentMapper.selectList(baseStudentLambdaQueryWrapper2);

                    PageHelper.startPage(pageNum, pageSize);

                    if (baseSubjectReq.getZb() != null) {
                        baseStudentList = baseMapper.selectBaseStudentListByZb(baseSubject.getId(), raecId, schoolId, baseSubjectReq.getZb());

                    } else {
                        baseStudentList = baseMapper.selectBaseStudentList2(baseSubject.getId(), raecId, schoolId);

                    }
                }
            } else {
                PageHelper.startPage(pageNum, pageSize);
                baseStudentList = baseMapper.selectBaseStudentList(baseSubject.getId(), raecId, schoolId);
            }


            List<BaseSchool> baseSchoolList = new ArrayList<>();
            if (baseStudentList.size() > 0) {
                LambdaQueryWrapper<BaseSchool> baseSchoolLambdaQueryWrapper = new LambdaQueryWrapper<>();
                baseSchoolLambdaQueryWrapper.in(BaseSchool::getId, baseStudentList.stream().map(BaseStudent::getSchoolId).collect(Collectors.toList()));
                baseSchoolList = baseSchoolMapper.selectList(baseSchoolLambdaQueryWrapper);
                Map<Long, BaseSchool> baseSchoolMap = baseSchoolList.stream().collect(Collectors.toMap(BaseSchool::getId, o -> o));

                LambdaQueryWrapper<Ochestrate> ochestrateLambdaQueryWrapper = new LambdaQueryWrapper<>();
                ochestrateLambdaQueryWrapper.in(Ochestrate::getObjectId, baseStudentList.stream().map(BaseStudent::getId).collect(Collectors.toList()));
                ochestrateLambdaQueryWrapper.eq(Ochestrate::getObjectType, 1L);
                ochestrateLambdaQueryWrapper.eq(Ochestrate::getSubId, baseSubject.getId());
                List<Ochestrate> ochestrateList = ochestrateMapper.selectList(ochestrateLambdaQueryWrapper);
                Map<Long, Ochestrate> ochestrateMap = ochestrateList.stream().collect(Collectors.toMap(Ochestrate::getObjectId, o -> o));
                total = new PageInfo(baseStudentList).getTotal();
                for (int i = 0; i < baseStudentList.size(); i++) {
                    BaseStudent baseStudent = baseStudentList.get(i);
                    OrchestrateRes orchestrate = new OrchestrateRes();

                    orchestrate.setObjectType(1L);
                    orchestrate.setObjectId(baseStudent.getId());
                    orchestrate.setAvatarSrc(baseStudent.getAvatarSrc());
                    orchestrate.setName(baseStudent.getName());
                    orchestrate.setUnitName(baseSchoolMap.get(baseStudent.getSchoolId()).getName());
                    orchestrate.setSubId(baseSubject.getId());
                    orchestrate.setSubName(baseSubject.getName());
                    orchestrate.setSex(baseStudent.getSex());
                    orchestrate.setSchoolId(baseStudent.getSchoolId());
                    if (ochestrateMap.get(baseStudent.getId()) != null) {
                        orchestrate.setNo(ochestrateMap.get(baseStudent.getId()).getNo());
                        orchestrate.setZb(ochestrateMap.get(baseStudent.getId()).getZb());
                        orchestrate.setXh(ochestrateMap.get(baseStudent.getId()).getXh());
                    }
                    orchestrateList.add(orchestrate);
                }
            }

        }
        //集体项目
        else if (Integer.valueOf(2).equals(baseSubject.getType())) {
//            LambdaQueryWrapper<BaseSchool> baseStudentLambdaQueryWrapper = new LambdaQueryWrapper<>();
////            baseStudentLambdaQueryWrapper.eq(BaseStudent::getOneConfirm,1);
//            baseStudentLambdaQueryWrapper.eq(BaseSchool::getRaceId, raecId);
//            baseStudentLambdaQueryWrapper.orderByAsc(BaseSchool::getSort);
//            if (baseSubjectReq.getSchoolId() != null) {
//                baseStudentLambdaQueryWrapper.eq(BaseSchool::getId, baseSubjectReq.getSchoolId());
//            }
            PageHelper.startPage(pageNum, pageSize);
            List<BaseSchool> baseSchoolList = baseMapper.selectBaseSschoolList(baseSubject.getId(), raecId, baseSubjectReq.getSchoolId());
            total = new PageInfo(baseSchoolList).getTotal();

            if (baseSchoolList.size() > 0) {
                LambdaQueryWrapper<Ochestrate> ochestrateLambdaQueryWrapper = new LambdaQueryWrapper<>();
                ochestrateLambdaQueryWrapper.in(Ochestrate::getObjectId, baseSchoolList.stream().map(BaseSchool::getId).collect(Collectors.toList()));
                ochestrateLambdaQueryWrapper.eq(Ochestrate::getObjectType, 2L);
                ochestrateLambdaQueryWrapper.eq(Ochestrate::getSubId, baseSubject.getId());
                List<Ochestrate> ochestrateList = ochestrateMapper.selectList(ochestrateLambdaQueryWrapper);
                Map<Long, Ochestrate> ochestrateMap = ochestrateList.stream().collect(Collectors.toMap(Ochestrate::getObjectId, o -> o));

                for (int i = 0; i < baseSchoolList.size(); i++) {
                    BaseSchool baseSchool = baseSchoolList.get(i);
                    OrchestrateRes orchestrate = new OrchestrateRes();
                    orchestrate.setObjectId(baseSchool.getId());
                    orchestrate.setSubId(baseSubject.getId());
                    orchestrate.setSubName(baseSubject.getName());
                    orchestrate.setObjectType(2L);
                    orchestrate.setAvatarSrc(baseSchool.getBadgeSrc());
                    orchestrate.setName(baseSchool.getName());
                    orchestrate.setUnitName(baseSchool.getName());
                    orchestrate.setSchoolId(baseSchool.getId());

                    if (ochestrateMap.get(baseSchool.getId()) != null) {
                        orchestrate.setNo(ochestrateMap.get(baseSchool.getId()).getNo());
                    }
                    orchestrateList.add(orchestrate);
                }
            }

        }
        //如果抽人项目
        else if (Integer.valueOf(1).equals(baseSubject.getLottery())) {
            PageHelper.startPage(pageNum, pageSize);
            List<BaseStudent> baseStudentList = baseMapper.selectBaseStudentList(baseSubject.getId(), raecId, schoolId);


            List<BaseSchool> baseSchoolList = new ArrayList<>();
            if (baseStudentList.size() > 0) {
                LambdaQueryWrapper<BaseSchool> baseSchoolLambdaQueryWrapper = new LambdaQueryWrapper<>();
                baseSchoolLambdaQueryWrapper.in(BaseSchool::getId, baseStudentList.stream().map(BaseStudent::getSchoolId).collect(Collectors.toList()));
                baseSchoolList = baseSchoolMapper.selectList(baseSchoolLambdaQueryWrapper);
                Map<Long, BaseSchool> baseSchoolMap = baseSchoolList.stream().collect(Collectors.toMap(BaseSchool::getId, o -> o));

                LambdaQueryWrapper<Ochestrate> ochestrateLambdaQueryWrapper = new LambdaQueryWrapper<>();
                ochestrateLambdaQueryWrapper.in(Ochestrate::getObjectId, baseStudentList.stream().map(BaseStudent::getId).collect(Collectors.toList()));
                ochestrateLambdaQueryWrapper.eq(Ochestrate::getObjectType, 1L);
                ochestrateLambdaQueryWrapper.eq(Ochestrate::getSubId, baseSubject.getId());
                List<Ochestrate> ochestrateList = ochestrateMapper.selectList(ochestrateLambdaQueryWrapper);
                Map<Long, Ochestrate> ochestrateMap = ochestrateList.stream().collect(Collectors.toMap(Ochestrate::getObjectId, o -> o));

                Map<Long, BaseSubject> subMap = new HashMap<>();


                List<Long> SubIdList = ochestrateList.stream().map(Ochestrate::getElectiveSubId).filter(Objects::nonNull).collect(Collectors.toList());
                if (SubIdList.size() > 0) {
                    List<BaseSubject> baseSubjectList = new ArrayList<>();
                    LambdaQueryWrapper<BaseSubject> baseSubjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    baseSubjectLambdaQueryWrapper.in(BaseSubject::getId, SubIdList);
                    baseSubjectList = baseSubjectMapper.selectList(baseSubjectLambdaQueryWrapper);
                    subMap = baseSubjectList.stream().collect(Collectors.toMap(BaseSubject::getId, o -> o));
                }
                total = new PageInfo(baseStudentList).getTotal();
                for (int i = 0; i < baseStudentList.size(); i++) {
                    BaseStudent baseStudent = baseStudentList.get(i);
                    OrchestrateRes orchestrate = new OrchestrateRes();
                    orchestrate.setObjectType(1L);
                    orchestrate.setObjectId(baseStudent.getId());
                    orchestrate.setAvatarSrc(baseStudent.getAvatarSrc());
                    orchestrate.setName(baseStudent.getName());
                    orchestrate.setSex(baseStudent.getSex());
                    orchestrate.setUnitName(baseSchoolMap.get(baseStudent.getSchoolId()).getName());
                    orchestrate.setSubId(baseSubject.getId());

                    orchestrate.setSchoolId(baseStudent.getSchoolId());
                    orchestrate.setLottery(1);

                    if (ochestrateMap.get(baseStudent.getId()) != null) {
                        orchestrate.setNo(ochestrateMap.get(baseStudent.getId()).getNo());
                        orchestrate.setElectiveSubId(ochestrateMap.get(baseStudent.getId()).getElectiveSubId());
                        if (subMap.get(ochestrateMap.get(baseStudent.getId()).getElectiveSubId()) != null) {
                            orchestrate.setSubName(subMap.get(ochestrateMap.get(baseStudent.getId()).getElectiveSubId()).getName());
                        }

                    }
                    if (orchestrate.getElectiveSubId() != null && subMap.get(orchestrate.getElectiveSubId()) != null) {
                        orchestrate.setSubName(subMap.get(orchestrate.getElectiveSubId()).getName());
                    }
                    orchestrateList.add(orchestrate);
                }
            }
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(orchestrateList);
        rspData.setTotal(total);
        return rspData;
    }

    @Override
    public AjaxResult update(OrchestrateRes orchestrateRes) {
        LambdaQueryWrapper<Ochestrate> ochestrateLambdaQueryWrapper = new LambdaQueryWrapper<Ochestrate>();
        ochestrateLambdaQueryWrapper.eq(Ochestrate::getSubId, orchestrateRes.getSubId());
        ochestrateLambdaQueryWrapper.eq(Ochestrate::getObjectId, orchestrateRes.getObjectId());
        ochestrateLambdaQueryWrapper.eq(Ochestrate::getObjectType, orchestrateRes.getObjectType());
        Ochestrate ochestrate = ochestrateMapper.selectOne(ochestrateLambdaQueryWrapper);
        if (ochestrate != null) {
            ochestrate.setNo(orchestrateRes.getNo());
            ochestrateMapper.updateById(ochestrate);
        } else {
            ochestrateMapper.insert(orchestrateRes);
        }


        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult lottery(OrchestrateRes orchestrateRes) {
        if (orchestrateRes.getNo() != null) {
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return AjaxResult.success("已抽过签", orchestrateRes);
        }
        Integer bhResult = 0;
        BaseSubject baseSubject = baseSubjectMapper.selectById(orchestrateRes.getSubId());

        if (baseSubject.getLottery() != null && baseSubject.getLottery() == 1) {
            BaseStudent baseStudent = baseStudentMapper.selectById(orchestrateRes.getObjectId());
            OrchestrateReq orchestrateReq = new OrchestrateReq();
            BeanUtils.copyProperties(orchestrateRes, orchestrateReq);
            TableDataInfo tableDataInfo = list(orchestrateReq, 1, 1000);
            if (tableDataInfo.getRows() != null && tableDataInfo.getRows().size() > 0) {
                List<OrchestrateRes> orchestrateResList = (List<OrchestrateRes>) tableDataInfo.getRows();
//                List<Long> electiveSubIdList = orchestrateResList.stream().map(Ochestrate::getElectiveSubId).filter(e -> e != null).collect(Collectors.toList());
//                Map<Long, Integer> subCountMap = new HashMap<>();
//                for (int i = 0; i < electiveSubIdList.size(); i++) {
//                    if (subCountMap.get(electiveSubIdList.get(i)) == null) {
//                        subCountMap.put(electiveSubIdList.get(i), 1);
//                    } else {
//                        int count = subCountMap.get(electiveSubIdList.get(i));
//                        count++;
//                        subCountMap.put(electiveSubIdList.get(i), count);
//                    }
//                }

                LambdaQueryWrapper<BaseSubject> baseSubjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
                baseSubjectLambdaQueryWrapper.eq(BaseSubject::getParentId, baseSubject.getId());
                List<BaseSubject> childBaseSubjectList = baseSubjectMapper.selectList(baseSubjectLambdaQueryWrapper);
                Map<Long, BaseSubject> subjectHashMap = childBaseSubjectList.stream().collect(Collectors.toMap(BaseSubject::getId, e1 -> e1));


                List<List<Long>> countList = new ArrayList<>();
                countList.add(new ArrayList<>());
                countList.add(new ArrayList<>());
                countList.add(new ArrayList<>());

                for (int i = 0; i < childBaseSubjectList.size(); i++) {
                    BaseSubject childBaseSubject = childBaseSubjectList.get(i);
                    String stuRule = childBaseSubject.getStuRule().trim();
                    if (stuRule.contains("+")) {
                        Map<String, Integer> subCountMap = new HashMap<>();
                        String[] strs = stuRule.split("\\+");
                        for (int j = 0; j < orchestrateResList.size(); j++) {
                            OrchestrateRes orchestrateRes1 = orchestrateResList.get(j);
                            Long electiveSubId = orchestrateResList.get(j).getElectiveSubId();
                            if (electiveSubId == null || !electiveSubId.equals(childBaseSubject.getId())) {
                                continue;
                            }
                            String key = orchestrateRes1.getSex() + "-" + electiveSubId;
                            if (subCountMap.get(key) == null) {
                                subCountMap.put(key, 1);
                            } else {
                                int count = subCountMap.get(key);
                                count++;
                                subCountMap.put(key, count);
                            }
                        }


                        Integer maleCount = Integer.parseInt(strs[0]);
                        List<Long> maleSubList = countList.get(1);
                        for (int j = 0; j < maleCount; j++) {
                            String key = "0-" + childBaseSubject.getId();
                            int count = 0;
                            if (subCountMap.get(key) != null) {
                                count = subCountMap.get(key);
                            }
                            if (count == 0) {
                                maleSubList.add(childBaseSubject.getId());
                            } else {
                                count--;
                                subCountMap.put(key, count);
                            }
                        }

                        Integer feMaleCount = Integer.parseInt(strs[1]);
                        List<Long> feMaleSubList = countList.get(2);
                        for (int j = 0; j < feMaleCount; j++) {
                            String key = "1-" + childBaseSubject.getId();
                            int count = 0;
                            if (subCountMap.get(key) != null) {
                                count = subCountMap.get(key);
                            }
                            if (count == 0) {
                                feMaleSubList.add(childBaseSubject.getId());
                            } else {
                                count--;
                                subCountMap.put(key, count);
                            }
                        }
                    } else {
                        Integer maleCount = Integer.parseInt(stuRule);
                        List<Long> subList = countList.get(0);
                        Map<Long, Integer> subCountMap = new HashMap<>();
                        for (int j = 0; j < orchestrateResList.size(); j++) {
                            Long electiveSubId = orchestrateResList.get(j).getElectiveSubId();
                            if (electiveSubId == null || !electiveSubId.equals(childBaseSubject.getId())) {
                                continue;
                            }
                            if (subCountMap.get(electiveSubId) == null) {
                                subCountMap.put(electiveSubId, 1);
                            } else {
                                int count = subCountMap.get(electiveSubId);
                                count++;
                                subCountMap.put(electiveSubId, count);
                            }
                        }
                        for (int j = 0; j < maleCount; j++) {
                            int count = 0;
                            if (subCountMap.get(childBaseSubject.getId()) != null) {
                                count = subCountMap.get(childBaseSubject.getId());
                            }
                            if (count == 0) {
                                subList.add(childBaseSubject.getId());
                            } else {
                                count--;
                                subCountMap.put(childBaseSubject.getId(), count);
                            }
                        }
                    }
                }
                Long subId = 0L;
                if (countList.get(0).size() == 0) {
                    List<Long> childCountList = new ArrayList<>();
                    if (baseStudent.getSex() == 0) {
                        childCountList = countList.get(1);
                    }
                    if (baseStudent.getSex() == 1) {
                        childCountList = countList.get(2);
                    }
                    if (childCountList.size() == 0) {
                        return AjaxResult.success("已抽过签", orchestrateRes);
                    }
                    Collections.shuffle(childCountList);
                    subId = childCountList.get(0);
                } else {
                    List<Long> childCountList = countList.get(0);
                    if (childCountList.size() == 0) {
                        return AjaxResult.success("已抽过签", orchestrateRes);
                    }
                    Collections.shuffle(childCountList);
                    subId = childCountList.get(0);
                }
                orchestrateRes.setElectiveSubId(subId);
                if (subjectHashMap.get(subId) != null) {
                    orchestrateRes.setSubName(subjectHashMap.get(subId).getName());
                }
                update(orchestrateRes);
                bhResult = orchestrateRes.getXh();
            }

        } else {
            OrchestrateReq orchestrateReq = new OrchestrateReq();
            BeanUtils.copyProperties(orchestrateRes, orchestrateReq);
            //不分学校随机抽签
            orchestrateReq.setSchoolId(null);
            TableDataInfo tableDataInfo = list(orchestrateReq, 1, 1000);
            if (tableDataInfo.getRows() != null && tableDataInfo.getRows().size() > 0) {
                if ("lsmp".equals(baseSubject.getCode())) {
                    List<OrchestrateRes> orchestrateResList = (List<OrchestrateRes>) tableDataInfo.getRows();
                    int maleCount = orchestrateResList.stream().filter(e -> e.getSex().equals(0)).collect(Collectors.toList()).size();
                    orchestrateResList = orchestrateResList.stream().filter(e -> e.getSex().equals(orchestrateRes.getSex())).collect(Collectors.toList());
                    List<Integer> bhList = orchestrateResList.stream().filter(e -> e.getNo() != null).map(Ochestrate::getNo).collect(Collectors.toList());
                    int bh = 0;
                    if (orchestrateRes.getSex().equals(1)) {
                        if (bhList.size() == orchestrateResList.size()) {
                            return AjaxResult.success("已抽完签号", orchestrateRes);
                        }
                        bh = LotteryUtil.lottery(orchestrateResList.size(), maleCount, bhList);
                    } else {
                        if (bhList.size() == orchestrateResList.size()) {
                            return AjaxResult.success("已抽完签号", orchestrateRes);
                        }
                        bh = LotteryUtil.lottery(orchestrateResList.size(), bhList);
                    }

                    int zb = bh / 5 + 1;
                    int xh = bh - 5 * (zb - 1);
                    if (xh == 0) {
                        zb--;
                        xh = 5;
                    }
                    orchestrateRes.setNo(bh);
                    orchestrateRes.setZb(zb);
                    orchestrateRes.setXh(xh);
                    update(orchestrateRes);
                    bhResult = xh;
                } else if ("pdjx".equals(baseSubject.getCode())) {
                    List<OrchestrateRes> orchestrateResList = (List<OrchestrateRes>) tableDataInfo.getRows();
                    List<Integer> bhList = orchestrateResList.stream().filter(e1 -> e1.getNo() != null).map(Ochestrate::getNo).collect(Collectors.toList());
                    if (bhList.size() == orchestrateResList.size()) {
                        return AjaxResult.success("已抽完签号", orchestrateRes);
                    }
                    int bh = LotteryUtil.lottery(orchestrateResList.size(), bhList);
                    int zb = bh / 15 + 1;
                    int xh = bh - 15 * (zb - 1);
                    if (xh == 0) {
                        zb--;
                        xh = 15;
                    }
                    orchestrateRes.setZb(zb);
                    orchestrateRes.setXh(xh);
                    orchestrateRes.setNo(bh);
                    update(orchestrateRes);
                    bhResult = bh;
                } else {
                    List<OrchestrateRes> orchestrateResList = (List<OrchestrateRes>) tableDataInfo.getRows();
                    List<Integer> bhList = orchestrateResList.stream().filter(e1 -> e1.getNo() != null).map(Ochestrate::getNo).collect(Collectors.toList());
                    if (bhList.size() == orchestrateResList.size()) {
                        return AjaxResult.success("已抽完签号", orchestrateRes);
                    }
                    int bh = LotteryUtil.lottery(orchestrateResList.size(), bhList);
                    orchestrateRes.setNo(bh);
                    update(orchestrateRes);
                    bhResult = bh;
                }
            }

        }

        return AjaxResult.success("操作成功", orchestrateRes);
    }

    @Override
    public void outputExcel(HttpServletResponse response) throws IOException {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //获取所有学校：
        LambdaQueryWrapper<BaseSchool> baseSchoolLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseSchoolLambdaQueryWrapper.eq(BaseSchool::getRaceId, loginUser.getSelectRaceId());
        baseSchoolLambdaQueryWrapper.orderByAsc(BaseSchool::getSort);
        PageHelper.startPage(1, 1000);
        List<BaseSchool> baseSchoolList = baseSchoolMapper.selectList(baseSchoolLambdaQueryWrapper);

        LambdaQueryWrapper<BaseStudent> baseStudentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        baseStudentLambdaQueryWrapper.eq(BaseStudent::getRaceId, loginUser.getSelectRaceId());
        baseStudentLambdaQueryWrapper.eq(BaseStudent::getTwoConfirm, 1);
        PageHelper.startPage(1, 1000);
        List<BaseStudent> baseStudentList = baseStudentMapper.selectList(baseStudentLambdaQueryWrapper);
        Map<Long, List<BaseStudent>> baseStudentMap = baseStudentList.stream().collect(Collectors.groupingBy(BaseStudent::getSchoolId));

        //获取成绩
        LambdaQueryWrapper<Ochestrate> ochestrateLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (baseStudentList.size() > 0) {
            ochestrateLambdaQueryWrapper.and(new Consumer<LambdaQueryWrapper<Ochestrate>>() {
                @Override
                public void accept(LambdaQueryWrapper<Ochestrate> ochestrateWrapper) {
                    ochestrateWrapper.eq(Ochestrate::getObjectType, 1);
                    ochestrateWrapper.in(Ochestrate::getObjectId, baseStudentList.stream().map(BaseStudent::getId).collect(Collectors.toList()));
                }
            });
        }

        if (baseSchoolList.size() > 0) {
            ochestrateLambdaQueryWrapper.or(new Consumer<LambdaQueryWrapper<Ochestrate>>() {
                @Override
                public void accept(LambdaQueryWrapper<Ochestrate> ochestrateWrapper) {
                    ochestrateWrapper.eq(Ochestrate::getObjectType, 2);
                    ochestrateWrapper.in(Ochestrate::getObjectId, baseSchoolList.stream().map(BaseSchool::getId).collect(Collectors.toList()));
                }
            });
        }

        Map<String, Ochestrate> totalOchestrateMap = new HashMap<>();
        List<Ochestrate> ochestrates = ochestrateMapper.selectList(ochestrateLambdaQueryWrapper);
        for (int i = 0; i < ochestrates.size(); i++) {
            if (ochestrates.get(i).getObjectType() == 1) {
                Long stuId = ochestrates.get(i).getObjectId();
                String key = "1" + "-" + stuId + "-" + ochestrates.get(i).getSubId();
                if (totalOchestrateMap.get(key) == null) {
                    totalOchestrateMap.put(key, ochestrates.get(i));
                } else {
                    totalOchestrateMap.put(key, ochestrates.get(i));
                }
            }
            if (ochestrates.get(i).getObjectType() == 2) {
                Long schoolId = ochestrates.get(i).getObjectId();
                String key = "2" + "-" + schoolId + "-" + ochestrates.get(i).getSubId();
                if (totalOchestrateMap.get(key) == null) {
                    totalOchestrateMap.put(key, ochestrates.get(i));
                } else {
                    totalOchestrateMap.put(key, ochestrates.get(i));
                }
            }
        }

        List<BaseSubject> baseSubjectList = baseSubjectMapper.selectBaseSubjectList(new BaseSubject());
        List<BaseSubject> tuanDuiBaseSubjectList = baseSubjectList.stream().filter(e -> e.getType() != null && 2 == e.getType()).collect(Collectors.toList());
        List<BaseSubject> soloBaseSubjectList = baseSubjectList.stream().filter(e -> e.getType() != null && 1 == e.getType()).collect(Collectors.toList());

        // 创建Excel工作簿对象
        Workbook wb = new XSSFWorkbook();
        // 创建单元格样式
        CellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER); // 水平居中
        style.setVerticalAlignment(VerticalAlignment.CENTER); // 垂直居中
        // 创建边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);

        // 创建第一个sheet页
        Sheet tuanDuiSheet = wb.createSheet("团队项目");
        // 在第一个sheet页中创建行和单元格
        Row row = tuanDuiSheet.createRow(0);
        Cell cell = row.createCell(0);
        cell.setCellValue("学校参赛顺序抽签登记表");
        cell.setCellStyle(style);
        // 设置行高：height = 磅 * 20 （1磅=0.353毫米=20缇）-> POI中行高是"缇(twips)"
        row.setHeight((short) (25 * 20));

        // 创建一个表示单元格范围的对象，参数分别是：起始行号，结束行号，起始列号，结束列号
        CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 2 + tuanDuiBaseSubjectList.size()); // 合并第一行的前三个单元格
        tuanDuiSheet.addMergedRegion(cellRangeAddress);

        // 设置合并后单元格的边框
        for (int i = 0; i <= cellRangeAddress.getLastColumn(); i++) {
            Cell mergedCell = row.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
            mergedCell.setCellStyle(style);
        }

        row = tuanDuiSheet.createRow(1);
        cell = row.createCell(0);
        cell.setCellValue("序号");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("id");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("学校名称");
        cell.setCellStyle(style);

        // 设置第一列的宽度为宽度（字符宽度的3/256的200倍）
        tuanDuiSheet.setColumnWidth(2, 10000);

        for (int i = 0; i < tuanDuiBaseSubjectList.size(); i++) {
            cell = row.createCell(3 + i);
            cell.setCellValue(tuanDuiBaseSubjectList.get(i).getName());
            cell.setCellStyle(style);
        }

        for (int i = 0; i < baseSchoolList.size(); i++) {
            BaseSchool baseSchool = baseSchoolList.get(i);
            row = tuanDuiSheet.createRow(2 + i);
            cell = row.createCell(0);
            cell.setCellStyle(style);
            cell.setCellValue(baseSchool.getSort());
            cell = row.createCell(1);
            cell.setCellStyle(style);
            cell.setCellValue(baseSchool.getId());
            cell = row.createCell(2);
            cell.setCellStyle(style);
            cell.setCellValue(baseSchool.getName());
            cell.setCellStyle(style);

            for (int j = 0; j < tuanDuiBaseSubjectList.size(); j++) {
                cell = row.createCell(3 + j);
                cell.setCellStyle(style);
                Ochestrate ochestrate = totalOchestrateMap.get("2" + "-" + baseSchool.getId() + "-" + tuanDuiBaseSubjectList.get(j).getId());
                if (ochestrate != null) {
                    cell.setCellValue(ochestrate.getNo() + "");
                    cell.setCellStyle(style);
                }

            }
        }

        for (int i = 0; i < baseSchoolList.size(); i++) {
            BaseSchool baseSchool = baseSchoolList.get(i);
            // 创建第二个sheet页
            Sheet childSheet = wb.createSheet("(" + baseSchool.getSort() + ")" + baseSchool.getName());
            row = childSheet.createRow(0);
            row.setHeight((short) (25 * 20));
            cell = row.createCell(0);
            cell.setCellValue("学生参赛顺序抽签登记表");
            cell.setCellStyle(style);
            // 创建一个表示单元格范围的对象，参数分别是：起始行号，结束行号，起始列号，结束列号
            cellRangeAddress = new CellRangeAddress(0, 0, 0, 3 + soloBaseSubjectList.size()); // 合并第一行的前三个单元格
            childSheet.addMergedRegion(cellRangeAddress);
            // 设置合并后单元格的边框
            for (int j = 0; j <= cellRangeAddress.getLastColumn(); j++) {
                Cell mergedCell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                mergedCell.setCellStyle(style);
            }

            row = childSheet.createRow(1);
            cell = row.createCell(0);
            cell.setCellValue("学校：" + baseSchool.getName());
            cell.setCellStyle(style);
            cellRangeAddress = new CellRangeAddress(1, 1, 0, 3 + soloBaseSubjectList.size()); // 合并第一行的前三个单元格
            childSheet.addMergedRegion(cellRangeAddress);
            // 设置合并后单元格的边框
            for (int j = 0; j <= cellRangeAddress.getLastColumn(); j++) {
                Cell mergedCell = row.getCell(j, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
                mergedCell.setCellStyle(style);
            }

            row = childSheet.createRow(2);
            cell = row.createCell(0);
            cell.setCellValue("序号");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("id");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("性别");
            cell.setCellStyle(style);

            for (int j = 0; j < soloBaseSubjectList.size(); j++) {
                cell = row.createCell(4 + j);
                cell.setCellValue(soloBaseSubjectList.get(j).getName());
                cell.setCellStyle(style);
            }

            List<BaseStudent> childBaseStudents = baseStudentMap.get(baseSchool.getId());
            if (childBaseStudents != null) {
                for (int j = 0; j < childBaseStudents.size(); j++) {
                    BaseStudent baseStudent = childBaseStudents.get(j);
                    row = childSheet.createRow(3 + j);
                    cell = row.createCell(0);
                    cell.setCellValue(j + 1);
                    cell.setCellStyle(style);

                    cell = row.createCell(1);
                    cell.setCellValue(baseStudent.getId());
                    cell.setCellStyle(style);

                    cell = row.createCell(2);
                    cell.setCellValue(baseStudent.getName());
                    cell.setCellStyle(style);

                    cell = row.createCell(3);
                    cell.setCellValue(baseStudent.getSex() == 0 ? "男" : "女");
                    cell.setCellStyle(style);

                    cell.setCellValue(baseStudent.getSex() == 0 ? "男" : "女");
                    cell.setCellStyle(style);

                    for (int k = 0; k < soloBaseSubjectList.size(); k++) {
                        Ochestrate ochestrate = totalOchestrateMap.get("1" + "-" + baseStudent.getId() + "-" + soloBaseSubjectList.get(k).getId());
                        if (ochestrate != null) {
                            cell = row.createCell(4 + k);
                            cell.setCellValue(ochestrate.getNo() + "");
                            cell.setCellStyle(style);
                        } else {
                            cell = row.createCell(4 + k);
                            cell.setCellStyle(style);
                        }

                    }
                }
            }

        }

        // 导出Excel文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        wb.write(response.getOutputStream());
        wb.close();
    }

    @Override
    public void outputJianlu(HttpServletResponse response, Long subId) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long raceId = loginUser.getSelectRaceId();
        BaseRace baseRace = baseRaceMapper.selectById(raceId);
        BaseSubject baseSubject = baseSubjectMapper.selectById(subId);
        List<BaseSubject> baseSubjectList = new ArrayList<>();
        if (baseSubject.getLottery() == 1) {
            LambdaQueryWrapper<BaseSubject> baseSubjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            baseSubjectLambdaQueryWrapper.eq(BaseSubject::getParentId, subId);
            baseSubjectList = baseSubjectMapper.selectList(baseSubjectLambdaQueryWrapper);
        }
        Map<Long, BaseSubject> baseSubjectMap = baseSubjectList.stream().collect(Collectors.toMap(BaseSubject::getId, e1 -> e1));


        OrchestrateReq orchestrateReq = new OrchestrateReq();
        orchestrateReq.setSubId(subId);
        TableDataInfo tableDataInfo = list(orchestrateReq, 1, 1000);

        List<OrchestrateRes> totalOrchestrateList = (List<OrchestrateRes>) tableDataInfo.getRows();
        XWPFDocument doc = new XWPFDocument();

        XWPFParagraph paragraph = doc.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = paragraph.createRun();
        run.setText(baseRace.getName());
        run.setFontSize(16); //设置字体大小 14
        run.setFontFamily("等线"); //设置字体为宋体
        run.setBold(true); //设置加粗

        paragraph = doc.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        run = paragraph.createRun();
        run.setText("检  录  表");
        run.setFontSize(14); //设置字体大小 14
        run.setFontFamily("等线"); //设置字体为宋体
        run.setBold(true); //设置加粗

        paragraph = doc.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.LEFT);
        run = paragraph.createRun();
        run.setText("科目：" + baseSubject.getName());
        run.setFontSize(12); //设置字体大小 14
        run.setFontFamily("等线"); //设置字体为宋体
        run.setBold(true); //设置加粗

        int width = 6;
        Map<Long, List<BaseStudent>> baseStudentMap = new HashMap<>();
        if (baseSubject.getType() == 2) {
            width++;
            LambdaQueryWrapper<BaseStudent> baseStudentLambdaQueryWrapper = new LambdaQueryWrapper<>();
            baseStudentLambdaQueryWrapper.eq(BaseStudent::getTwoConfirm, 1);
            List<Long> schoolIdList = totalOrchestrateList.stream().filter(e -> e.getObjectType() == 2).map(OrchestrateRes::getObjectId).collect(Collectors.toList());
            baseStudentLambdaQueryWrapper.in(BaseStudent::getSchoolId, schoolIdList);
            List<BaseStudent> baseStudentList = baseStudentMapper.selectList(baseStudentLambdaQueryWrapper);
            System.out.println(baseStudentList);
            baseStudentMap = baseStudentList.stream().collect(Collectors.groupingBy(BaseStudent::getSchoolId));
        }

        for (int i = 0; i < totalOrchestrateList.size(); i++) {
            if (totalOrchestrateList.get(i).getZb() == null) {
                totalOrchestrateList.get(i).setZb(-1);
            }
        }
        //分组
        Map<Integer, List<OrchestrateRes>> orchestrateResMap = totalOrchestrateList.stream().collect(Collectors.groupingBy(Ochestrate::getZb));
        for (Integer zb : orchestrateResMap.keySet()) {
            List<OrchestrateRes> orchestrateList = orchestrateResMap.get(zb);
            System.out.println("Key = " + zb + ", Value = " + orchestrateResMap.get(zb));
            if (zb != -1) {
                paragraph = doc.createParagraph();
                paragraph.setAlignment(ParagraphAlignment.LEFT);
                run = paragraph.createRun();
                run.setText("第" + zb + "组");
                run.setFontSize(12); //设置字体大小 14
                run.setFontFamily("等线"); //设置字体为宋体
                run.setBold(true); //设置加粗
            } else {
                paragraph = doc.createParagraph();
                paragraph.setAlignment(ParagraphAlignment.LEFT);
                run = paragraph.createRun();
                run.setText("");
                run.setFontSize(12); //设置字体大小 14
                run.setFontFamily("等线"); //设置字体为宋体
                run.setBold(true); //设置加粗
            }

            XWPFTable table = doc.createTable(orchestrateList.size() + 1, width);
            table.setTableAlignment(TableRowAlign.CENTER);
            table.setWidth("10000");
            int index = 0;
            //第一行数据
            table.getRow(0).getCell(index).setText("ID号");
            table.getRow(0).getCell(index).setWidth("10%");

            index++;
            table.getRow(0).getCell(index).setText("出场序号");
            table.getRow(0).getCell(index).setWidth("10%");

            if (baseSubject.getType() == 2) {
                index++;
                table.getRow(0).getCell(index).setText("成员id");
                table.getRow(0).getCell(index).setWidth("30%");
            }

            index++;
            table.getRow(0).getCell(index).setText("第一次检录");
            table.getRow(0).getCell(index).setWidth("10%");

            index++;
            table.getRow(0).getCell(index).setText("第二次检录");
            table.getRow(0).getCell(index).setWidth("10%");


            index++;
            table.getRow(0).getCell(index).setText("候场");
            table.getRow(0).getCell(index).setWidth("10%");

            index++;
            table.getRow(0).getCell(index).setText("备注");
            table.getRow(0).getCell(index).setWidth("10%");


            for (int i = 0; i < orchestrateList.size(); i++) {
                OrchestrateRes orchestrateRes = orchestrateList.get(i);
                index = 0;
                //第一行数据
                table.getRow(i + 1).getCell(index).setText(orchestrateRes.getObjectId() + "");
                table.getRow(i + 1).getCell(index).setWidth("10%");

                index++;
                table.getRow(i + 1).getCell(index).setText(orchestrateRes.getNo() + "");
                table.getRow(i + 1).getCell(index).setWidth("10%");

                if (baseSubject.getType() == 2) {
                    index++;

                    table.getRow(i + 1).getCell(index).setWidth("30%");
                    List<BaseStudent> baseStudentList = baseStudentMap.get(orchestrateRes.getObjectId());
                    String members = "";
                    for (int j = 0; j < baseStudentList.size(); j++) {
                        members += (baseStudentList.get(j).getId() + ",");
                    }
                    table.getRow(i + 1).getCell(index).setText(members);
                }

                index++;
                table.getRow(i + 1).getCell(index).setWidth("10%");

                index++;
                table.getRow(i + 1).getCell(index).setWidth("10%");

                index++;
                table.getRow(i + 1).getCell(index).setWidth("10%");

                index++;
                table.getRow(i + 1).getCell(index).setWidth("10%");
            }

            // 遍历表格的每一行
            for (int row = 0; row < table.getNumberOfRows(); row++) {
                // 遍历每一行的每一列
                for (int col = 0; col < table.getRow(row).getTableCells().size(); col++) {
                    XWPFTableCell cell = table.getRow(row).getCell(col);
                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                    XWPFParagraph paragraph1 = cell.getParagraphArray(0);
                    if (paragraph1 != null) {
                        paragraph1.setAlignment(ParagraphAlignment.CENTER);//水平居中对齐
                    }
                }
                table.getRow(row).setHeight(400); //设置高度
            }

            paragraph = doc.createParagraph();
            paragraph.setAlignment(ParagraphAlignment.RIGHT);
            run = paragraph.createRun();
            run.setText("签字：      ");
            run.setFontSize(12); //设置字体大小 14
            run.setFontFamily("等线"); //设置字体为宋体
            run.setBold(true); //设置加粗
        }




        // 导出Excel文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        doc.write(response.getOutputStream());

    }

//    @Override
//    public void outputJianlu(HttpServletResponse response, Long subId) throws IOException {
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        Long raceId = loginUser.getSelectRaceId();
//        BaseRace baseRace = baseRaceMapper.selectById(raceId);
//        BaseSubject baseSubject = baseSubjectMapper.selectById(subId);
//        List<BaseSubject> baseSubjectList = new ArrayList<>();
//        if (baseSubject.getLottery() == 1) {
//            LambdaQueryWrapper<BaseSubject> baseSubjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            baseSubjectLambdaQueryWrapper.eq(BaseSubject::getParentId, subId);
//            baseSubjectList = baseSubjectMapper.selectList(baseSubjectLambdaQueryWrapper);
//        }
//        Map<Long, BaseSubject> baseSubjectMap = baseSubjectList.stream().collect(Collectors.toMap(BaseSubject::getId, e1 -> e1));
//
//        OrchestrateReq orchestrateReq = new OrchestrateReq();
//        orchestrateReq.setSubId(subId);
//        TableDataInfo tableDataInfo = list(orchestrateReq, 1, 1000);
//
//        List<OrchestrateRes> orchestrateList = (List<OrchestrateRes>) tableDataInfo.getRows();
//        XWPFDocument doc = new XWPFDocument();
//
//        XWPFParagraph paragraph = doc.createParagraph();
//        paragraph.setAlignment(ParagraphAlignment.CENTER);
//        XWPFRun run = paragraph.createRun();
//        run.setText(baseRace.getName());
//        run.setFontSize(16); //设置字体大小 14
//        run.setFontFamily("等线"); //设置字体为宋体
//        run.setBold(true); //设置加粗
//
//        paragraph = doc.createParagraph();
//        paragraph.setAlignment(ParagraphAlignment.CENTER);
//        run = paragraph.createRun();
//        run.setText("检  录  表");
//        run.setFontSize(14); //设置字体大小 14
//        run.setFontFamily("等线"); //设置字体为宋体
//        run.setBold(true); //设置加粗
//
//        paragraph = doc.createParagraph();
//        paragraph.setAlignment(ParagraphAlignment.LEFT);
//        run = paragraph.createRun();
//        run.setText("科目：" + baseSubject.getName());
//        run.setFontSize(12); //设置字体大小 14
//        run.setFontFamily("等线"); //设置字体为宋体
//        run.setBold(true); //设置加粗
//
//
//        if (!"lsmp".equals(baseSubject.getCode())) {
//            XWPFTable table = doc.createTable(orchestrateList.size() + 1, 7);
//            table.setTableAlignment(TableRowAlign.CENTER);
//
//            table.setWidth("10000");
//            //第一行数据
//            if (baseSubject.getLottery() == 1) {
//                table.getRow(0).getCell(0).setText("项目");
//            } else {
//                table.getRow(0).getCell(0).setText("序号");
//            }
//            table.getRow(0).getCell(0).setWidth("10%");
//
//            if (baseSubject.getLottery() == 1) {
//                table.getRow(0).getCell(1).setText("姓名");
//            } else {
//                if (baseSubject.getType() == 1) {
//                    table.getRow(0).getCell(1).setText("姓名");
//                } else {
//                    table.getRow(0).getCell(1).setText("名称");
//                }
//            }
//            table.getRow(0).getCell(1).setWidth("20%");
//
//            table.getRow(0).getCell(2).setText("单位");
//            table.getRow(0).getCell(2).setWidth("30%");
//            table.getRow(0).getCell(3).setText("成绩");
//            table.getRow(0).getCell(3).setWidth("10%");
//            table.getRow(0).getCell(4).setText("得分");
//            table.getRow(0).getCell(4).setWidth("10%");
//            table.getRow(0).getCell(5).setText("名次");
//            table.getRow(0).getCell(5).setWidth("10%");
//            table.getRow(0).getCell(6).setText("备注");
//            table.getRow(0).getCell(6).setWidth("10%");
//            for (int i = 0; i < orchestrateList.size(); i++) {
//                OrchestrateRes orchestrateRes = orchestrateList.get(i);
//                if (baseSubject.getLottery() == 1) {
//                    if (orchestrateRes.getSubName() == null) {
//                        table.getRow(i + 1).getCell(0).setText("未抽签号");
//                    } else {
//                        table.getRow(i + 1).getCell(0).setText(orchestrateRes.getSubName() + "");
//                    }
//                } else {
//                    if (orchestrateRes.getNo() == null) {
//                        table.getRow(i + 1).getCell(0).setText("未抽签号");
//
//                    } else {
//                        table.getRow(i + 1).getCell(0).setText(orchestrateRes.getNo() + "");
//                    }
//                }
//
//                table.getRow(i + 1).getCell(0).setWidth("10%");
//
//                table.getRow(i + 1).getCell(1).setText(orchestrateRes.getName() + "");
//                table.getRow(i + 1).getCell(1).setWidth("20%");
//                table.getRow(i + 1).getCell(2).setText(orchestrateRes.getUnitName() + "");
//                table.getRow(i + 1).getCell(2).setWidth("30%");
//                table.getRow(i + 1).getCell(3).setText("");
//                table.getRow(i + 1).getCell(3).setWidth("10%");
//                table.getRow(i + 1).getCell(4).setText("");
//                table.getRow(i + 1).getCell(4).setWidth("10%");
//                table.getRow(i + 1).getCell(5).setText("");
//                table.getRow(i + 1).getCell(5).setWidth("10%");
//                table.getRow(i + 1).getCell(6).setText("");
//                table.getRow(i + 1).getCell(6).setWidth("10%");
//            }
//
//            // 遍历表格的每一行
//            for (int row = 0; row < table.getNumberOfRows(); row++) {
//                // 遍历每一行的每一列
//                for (int col = 0; col < table.getRow(row).getTableCells().size(); col++) {
//                    XWPFTableCell cell = table.getRow(row).getCell(col);
//                    cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
//                    XWPFParagraph paragraph1 = cell.getParagraphArray(0);
//                    if (paragraph1 != null) {
//                        paragraph1.setAlignment(ParagraphAlignment.CENTER);//水平居中对齐
//                    }
//                }
//                table.getRow(row).setHeight(400); //设置高度
//            }
//        } else {
//            List<Integer> zbList = orchestrateList.stream().map(OrchestrateRes::getZb).distinct().sorted().collect(Collectors.toList());
//            Map<Integer, List<OrchestrateRes>> ochestrateMap = orchestrateList.stream().collect(Collectors.groupingBy(Ochestrate::getZb));
//            for (int i = 0; i < zbList.size(); i++) {
//                paragraph = doc.createParagraph();
//                paragraph.setAlignment(ParagraphAlignment.LEFT);
//                run = paragraph.createRun();
//                run.setText("第" + zbList.get(i) + "组");
//                run.setFontSize(12); //设置字体大小 14
//                run.setFontFamily("等线"); //设置字体为宋体
//                run.setBold(true); //设置加粗
//                run = paragraph.createRun();
//                List<OrchestrateRes> childList = ochestrateMap.get(zbList.get(i));
//                XWPFTable table = doc.createTable(childList.size() + 1, 9);
//                table.setTableAlignment(TableRowAlign.CENTER);
//                table.setWidth("10000");
//
//                table.getRow(0).getCell(0).setText("序号");
//                table.getRow(0).getCell(0).setWidth("5%");
//                table.getRow(0).getCell(1).setText("组别");
//                table.getRow(0).getCell(1).setWidth("5%");
//                table.getRow(0).getCell(2).setText("组内号");
//                table.getRow(0).getCell(2).setWidth("5%");
//                table.getRow(0).getCell(3).setText("姓名");
//                table.getRow(0).getCell(3).setWidth("20%");
//                table.getRow(0).getCell(4).setText("单位");
//                table.getRow(0).getCell(4).setWidth("30%");
//                table.getRow(0).getCell(5).setText("成绩");
//                table.getRow(0).getCell(5).setWidth("10%");
//                table.getRow(0).getCell(6).setText("得分");
//                table.getRow(0).getCell(6).setWidth("10%");
//                table.getRow(0).getCell(7).setText("名次");
//                table.getRow(0).getCell(7).setWidth("5%");
//                table.getRow(0).getCell(8).setText("备注");
//                table.getRow(0).getCell(8).setWidth("10%");
//
//                for (int j = 0; j < childList.size(); j++) {
//                    OrchestrateRes orchestrateRes = childList.get(j);
//                    table.getRow(j + 1).getCell(0).setText(orchestrateRes.getNo() + "");
//                    table.getRow(j + 1).getCell(0).setWidth("5%");
//                    table.getRow(j + 1).getCell(1).setText(orchestrateRes.getZb() + "");
//                    table.getRow(j + 1).getCell(1).setWidth("5%");
//                    table.getRow(j + 1).getCell(2).setText(orchestrateRes.getXh() + "");
//                    table.getRow(j + 1).getCell(2).setWidth("5%");
//                    table.getRow(j + 1).getCell(3).setText(orchestrateRes.getName() + "");
//                    table.getRow(j + 1).getCell(3).setWidth("20%");
//                    table.getRow(j + 1).getCell(4).setText(orchestrateRes.getUnitName() + "");
//                    table.getRow(j + 1).getCell(4).setWidth("30%");
//                    table.getRow(j + 1).getCell(5).setText("");
//                    table.getRow(j + 1).getCell(5).setWidth("10%");
//                    table.getRow(j + 1).getCell(6).setText("");
//                    table.getRow(j + 1).getCell(6).setWidth("10%");
//                    table.getRow(j + 1).getCell(7).setText("");
//                    table.getRow(j + 1).getCell(7).setWidth("5%");
//                    table.getRow(j + 1).getCell(8).setText("");
//                    table.getRow(j + 1).getCell(8).setWidth("10%");
//                }
//                // 遍历表格的每一行
//                for (int row = 0; row < table.getNumberOfRows(); row++) {
//                    // 遍历每一行的每一列
//                    for (int col = 0; col < table.getRow(row).getTableCells().size(); col++) {
//                        XWPFTableCell cell = table.getRow(row).getCell(col);
//                        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
//                        XWPFParagraph paragraph1 = cell.getParagraphArray(0);
//                        if (paragraph1 != null) {
//                            paragraph1.setAlignment(ParagraphAlignment.CENTER);//水平居中对齐
//                        }
//                    }
//                    table.getRow(row).setHeight(400); //设置高度
//                }
//                run = paragraph.createRun();
//                run.setText("\n");
//                run = paragraph.createRun();
//                run.setText("\n");
//            }
//        }
//
//
//        // 导出Excel文件
//        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setCharacterEncoding("utf-8");
//        doc.write(response.getOutputStream());
//
//    }

    @Override
    public void outputLotteryWord(HttpServletResponse response, Long subId) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long raceId = loginUser.getSelectRaceId();
        BaseRace baseRace = baseRaceMapper.selectById(raceId);
        BaseSubject baseSubject = baseSubjectMapper.selectById(subId);
        List<BaseSubject> baseSubjectList = new ArrayList<>();
        if (baseSubject.getLottery() == 1) {
            LambdaQueryWrapper<BaseSubject> baseSubjectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            baseSubjectLambdaQueryWrapper.eq(BaseSubject::getParentId, subId);
            baseSubjectList = baseSubjectMapper.selectList(baseSubjectLambdaQueryWrapper);
        }
        Map<Long, BaseSubject> baseSubjectMap = baseSubjectList.stream().collect(Collectors.toMap(BaseSubject::getId, e1 -> e1));

        OrchestrateReq orchestrateReq = new OrchestrateReq();
        orchestrateReq.setSubId(subId);
        TableDataInfo tableDataInfo = list(orchestrateReq, 1, 1000);

        List<OrchestrateRes> orchestrateList = (List<OrchestrateRes>) tableDataInfo.getRows();
        XWPFDocument doc = new XWPFDocument();

        XWPFParagraph paragraph = doc.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        XWPFRun run = paragraph.createRun();
        run.setText(baseRace.getName());
        run.setFontSize(16); //设置字体大小 14
        run.setFontFamily("等线"); //设置字体为宋体
        run.setBold(true); //设置加粗

        paragraph = doc.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.CENTER);
        run = paragraph.createRun();
        run.setText("抽 签 登 记 表");
        run.setFontSize(14); //设置字体大小 14
        run.setFontFamily("等线"); //设置字体为宋体
        run.setBold(true); //设置加粗

        paragraph = doc.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.LEFT);
        run = paragraph.createRun();
        run.setText("科目：" + baseSubject.getName());
        run.setFontSize(12); //设置字体大小 14
        run.setFontFamily("等线"); //设置字体为宋体
        run.setBold(true); //设置加粗

        paragraph = doc.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.LEFT);
        run = paragraph.createRun();
        run.setText("抽签时间：" + sdf.format(new Date()));
        run.setFontSize(12); //设置字体大小 14
        run.setFontFamily("等线"); //设置字体为宋体
        run.setBold(true); //设置加粗

        int width = 5;
        if (baseSubject.getType() == null || baseSubject.getType() == 1) {
            width++;
        }
        XWPFTable table = doc.createTable(orchestrateList.size() + 1, width);
        table.setTableAlignment(TableRowAlign.CENTER);
        table.setWidth("10000");
        int index = 0;
        //第一行数据
        table.getRow(0).getCell(index).setText("ID号");
        table.getRow(0).getCell(index).setWidth("10%");

        index++;
        if (baseSubject.getLottery() == 1) {
            table.getRow(0).getCell(index).setText("姓名");
        } else {
            if (baseSubject.getType() == 1) {
                table.getRow(0).getCell(index).setText("姓名");
            } else {
                table.getRow(0).getCell(index).setText("名称");
            }
        }
        table.getRow(0).getCell(index).setWidth("20%");
        //个人项目
        if (baseSubject.getType() == null || baseSubject.getType() == 1) {
            index++;
            table.getRow(0).getCell(index).setText("性别");
            table.getRow(0).getCell(index).setWidth("10%");
        }

        index++;
        table.getRow(0).getCell(index).setText("单位");
        table.getRow(0).getCell(index).setWidth("30%");

        //第一行数据
        index++;
        if (baseSubject.getLottery() == 1) {
            table.getRow(0).getCell(index).setText("项目");
        } else {
            table.getRow(0).getCell(index).setText("序号");
        }
        table.getRow(0).getCell(index).setWidth("10%");

        index++;
        table.getRow(0).getCell(index).setText("备注");
        table.getRow(0).getCell(index).setWidth("10%");

        for (int i = 0; i < orchestrateList.size(); i++) {
            OrchestrateRes orchestrateRes = orchestrateList.get(i);
            index = 0;

            table.getRow(i + 1).getCell(index).setText(orchestrateRes.getObjectId() + "");
            table.getRow(i + 1).getCell(index).setWidth("10%");

            index++;
            table.getRow(i + 1).getCell(index).setText(orchestrateRes.getName() + "");
            table.getRow(i + 1).getCell(index).setWidth("20%");
            //个人项目
            if (baseSubject.getType() == null || baseSubject.getType() == 1) {
                index++;
                table.getRow(i + 1).getCell(index).setText(orchestrateRes.getSex() == 0 ? "男" : "女" + "");
                table.getRow(i + 1).getCell(index).setWidth("10%");
            }
            index++;
            table.getRow(i + 1).getCell(index).setText(orchestrateRes.getUnitName() + "");
            table.getRow(i + 1).getCell(index).setWidth("30%");
            index++;
            table.getRow(i + 1).getCell(index).setText("");
            table.getRow(i + 1).getCell(index).setWidth("10%");
            if (baseSubject.getLottery() == 1) {
                if (orchestrateRes.getSubName() == null) {
                    table.getRow(i + 1).getCell(index).setText("未抽项目");
                } else {
                    table.getRow(i + 1).getCell(index).setText(orchestrateRes.getSubName() + "");
                }
            } else {
                if (orchestrateRes.getNo() == null) {
                    table.getRow(i + 1).getCell(index).setText("未抽签号");

                } else {
                    table.getRow(i + 1).getCell(index).setText(orchestrateRes.getNo() + "");
                }
            }
            index++;
            table.getRow(i + 1).getCell(index).setText("");
            table.getRow(i + 1).getCell(index).setWidth("10%");
        }

        // 遍历表格的每一行
        for (int row = 0; row < table.getNumberOfRows(); row++) {
            // 遍历每一行的每一列
            for (int col = 0; col < table.getRow(row).getTableCells().size(); col++) {
                XWPFTableCell cell = table.getRow(row).getCell(col);
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
                XWPFParagraph paragraph1 = cell.getParagraphArray(0);
                if (paragraph1 != null) {
                    paragraph1.setAlignment(ParagraphAlignment.CENTER);//水平居中对齐
                }
            }
            table.getRow(row).setHeight(400); //设置高度
        }

        paragraph = doc.createParagraph();
        paragraph.setAlignment(ParagraphAlignment.RIGHT);
        run = paragraph.createRun();
        run.setText("云南省学校体育教学指导委员会：      ");
        run.setFontSize(12); //设置字体大小 14
        run.setFontFamily("等线"); //设置字体为宋体
        run.setBold(true); //设置加粗

        // 导出Excel文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        doc.write(response.getOutputStream());
    }
}
